package com.fireXXX.job.analysis.crawler.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;
import java.util.List;

/**
 * @description: TODO
 * @throws:
 * @author: zhuangzhang2
 * @date: 2020/04/15 15:11
 */
public class JacksonUtil {

    private static ObjectMapper objectMapper;

    static {
        objectMapper = Jackson2ObjectMapperBuilder.json().build();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /*
     * 1、对象类型使用BeanSerializer来序列化，调用BeanSerializer.resolve来构造JsonSerializer
     * 2、调用BeanSerializer.serialize的serializeFields来序列化对象的fields
     * 3、每个field的类型可以是StringSerializer(string)、IndexedStringListSerializer(arraylist类型)、BeanSerializer(对象类型)
     *
     * @author fireXXX
     * @date 2020/12/11 0:43
     * @param value
     * @return java.lang.String
     **/
    public static String toJsonString(Object value) throws JsonProcessingException {
        return objectMapper.writeValueAsString(value);
    }

    public static String toJsonStringSafe(Object value) {
        try {
            return objectMapper.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static <T> T toObject(String content, Class<T> type) throws IOException {
        return objectMapper.readValue(content, type);
    }

    public static <T> List<T> toObjectList(String content, Class<T> type) throws IOException {
        JavaType jt = objectMapper.getTypeFactory().constructParametricType(List.class, type);
        return objectMapper.readValue(content, jt);
    }

    public static <T> T toGenericObject(String content, TypeReference valueTypeRef) throws IOException {
        return (T) objectMapper.readValue(content, valueTypeRef);
    }

}